Python生成器对象send()方法用法

您所在的位置:网站首页 生成器send python Python生成器对象send()方法用法

Python生成器对象send()方法用法

2024-07-14 03:44| 来源: 网络整理| 查看: 265

关于生成器基本用法请参考详解Python生成器函数和生成器对象的原理和用法

>>> def f(): yield from 'abcdefg' #使用yield表达式创建生成器 >>> x = f() >>> next(x) 'a' >>> next(x) 'b' >>> for item in x: #输出x中的剩余元素 print(item, end=' ') c d e f g >>> def gen(): yield 1 yield 2 yield 3 >>> x, y, z = gen() #生成器对象支持序列解包

生成器对象还支持使用send()方法传入新值,从而改变后续生成的数据,这时要对yield表达式稍微改写一下。

>>> def gen(start, end): i = start while i < end: v = (yield i) if v: i = v else: i += 1 >>> g = gen(1, 101) >>> next(g) 1 >>> g.__next__() 2 >>> g.send(9) #传入新值,改变后续生成的数据 9 >>> next(g) 10



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3